import React, {PureComponent, Fragment} from 'react';
import {connect} from 'dva';
import {
	Row,
	Col,
	Card,
	Form,
	Input,
	Select,
	Icon,
	Button,
	Dropdown,
	Menu,
	DatePicker,
	Modal,
	message,
	Badge,
	Divider,
	Upload
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import {fetchPost} from '../../utils/utils';
import host from '../../services/host';
import {getAuthToken} from '../../utils/authority';

import styles from './TableList.less';

import config from '../../config';

const FormItem = Form.Item;
const confirm = Modal.confirm;
const pageSize = 5;
const {Option} = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
const statusMap = ['default', 'processing', 'success', 'error'];
const status = [
	'编辑中',
	'待审核',
	'已审核',
	'未通过',
	'已发布',
	'已下架'
];

const CreateForm = Form.create()(props => {
	const {modalVisible, form, handleAdd, handleModalVisible} = props;
	const okHandle = () => {
		form.validateFields((err, fieldsValue) => {
			if (err)
				return;
			form.resetFields();
			handleAdd(fieldsValue);
		});
	};
	return (<Modal title="新建规则" visible={modalVisible} onOk={okHandle} onCancel={() => handleModalVisible()}>
		<FormItem labelCol={{
				span: 5
			}} wrapperCol={{
				span: 15
			}} label="描述">
			{
				form.getFieldDecorator('desc', {
					rules: [
						{
							required: true,
							message: 'Please input some description...'
						}
					]
				})(<Input placeholder="请输入"/>)
			}
		</FormItem>
	</Modal>);
});

@connect(({article, loading}) => ({
	rule: {
		data: {
			list: article.list,
			pagination: article.pagination
		}
	},
	authors: article.authors,
	loading: loading.models.article,
	checkLoading: loading.effects['article/check']
}))
@Form.create()
export default class ArticleList extends PureComponent {
	state = {
		modalVisible: false,
		expandForm: false,
		selectedRows: [],
		formValues: {},
		visible: false,
		setModalVisible: true,
		fileList: [],
		checkItem: {
			title: '',
			content: '',
			id: '',
			cover: ''
		}
	};

	componentDidMount() {
		const {dispatch} = this.props;
		dispatch({
			type: 'article/fetch',
			payload: {
				count: pageSize,
				page: 1
			}
		});
		this.fetchAuthor();
	}

	fetchAuthor = () => {
		this.props.dispatch({type: 'article/fetchAuthor', payload: {}});
	};

	handleStandardTableChange = (pagination, filtersArg, sorter) => {
		const {dispatch} = this.props;
		const {formValues} = this.state;

		const filters = Object.keys(filtersArg).reduce((obj, key) => {
			const newObj = {
				...obj
			};
			newObj[key] = getValue(filtersArg[key]);
			return newObj;
		}, {});

		const params = {
			page: pagination.current,
			count: pagination.pageSize,
			...formValues,
			...filters
		};
		if (sorter.field) {
			params.sorter = `${sorter.field}_${sorter.order}`;
		}

		dispatch({type: 'article/fetch', payload: params});
	};

	handleFormReset = () => {
		const {form, dispatch} = this.props;
		form.resetFields();
		this.setState({formValues: {}});
		dispatch({type: 'article/fetch', payload: {}});
	};

	toggleForm = () => {
		this.setState({
			expandForm: !this.state.expandForm
		});
	};

	handleMenuClick = e => {
		const {dispatch} = this.props;
		const {selectedRows} = this.state;

		if (!selectedRows)
			return;

		switch (e.key) {
			case 'remove':
				dispatch({
					type: 'rule/remove',
					payload: {
						no: selectedRows.map(row => row.no).join(',')
					},
					callback: () => {
						this.setState({selectedRows: []});
					}
				});
				break;
			default:
				break;
		}
	};

	handleSelectRows = rows => {
		this.setState({selectedRows: rows});
	};

	handleSearch = e => {
		e.preventDefault();

		const {dispatch, form} = this.props;

		form.validateFields((err, fieldsValue) => {
			if (err)
				return;

			const values = {
				...fieldsValue,
				updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf()
			};

			this.setState({formValues: values});

			dispatch({type: 'article/fetch', payload: values});
		});
	};

	handleModalVisible = flag => {
		this.setState({
			modalVisible: !!flag
		});
	};

	handleAdd = fields => {
		this.props.dispatch({
			type: 'rule/add',
			payload: {
				description: fields.desc
			}
		});

		message.success('添加成功');
		this.setState({modalVisible: false});
	};

	handleDelete = (id) => {
		const my = this;
		const list = my.props.rule.data.list;
		confirm({
			title: '确定要删除该文章?',
			content: '如果这个文章已经发布到APP了，删除之后APP将不再显示',
			okText: "删除",
			cancelText: "取消",
			onOk() {
				return new Promise((resolve, reject) => {
					fetchPost(`${host.host}/bearadmin/article/delete`, {
						id: id,
						authToken: getAuthToken()
					}, (error, response) => {
						if (error === null) {
							for (let i = 0; i < list.length; i++) {
								if (list[i].id === id) {
									list.splice(i, 1);
								}
							}
							my.props.dispatch({type: 'article/updateListData', payload: list});
							resolve();
						} else {
							reject();
						}
					});
				}).catch(() => console.log('Oops errors!'));
			},
			onCancel() {}
		});
	};
	handleSubCheck = (id) => {
		this.props.dispatch({
			type: 'article/subCheck',
			payload: {
				article_id: id
			}
		});
	};
	handleCheck = (item) => {
		// const my = this;
		this.setState({
			visible: true,
			checkItem: {
				...item
			}
		});
	};
	handleAdopt = (id) => {
		this.props.dispatch({
			type: 'article/check',
			payload: {
				article_id: id,
				status: 3
			}
		});
	};
	handleNotThrough = (id) => {
		this.props.dispatch({
			type: 'article/check',
			payload: {
				article_id: id,
				status: 4
			}
		});
	};

	handleCheckOk = () => {
		this.setState({visible: false});
	};

	handleCheckCancel = () => {
		this.setState({visible: false});
	};

	settingForm() {
		const {getFieldDecorator} = this.props.form;
		const props = {
			name: 'file',
			action: config.upload_server_url,
			data: {
				accessToken: this.state.current_upload_access_token
			},
			multiple: true,
			listType: 'picture-card',
			fileList: this.state.fileList,
			onRemove: this.handleRemove,
			customRequest: this.handelCustomRequest
		};
		return (<Modal title="文章设置" visible={this.state.setModalVisible} onOk={this.handleOk}
			// confirmLoading={confirmLoading}
			onCancel={this.handleCancel}>
			<Col>
				<Row>
					<div style={{
							padding: 20
						}}>推荐封面图</div>
				</Row>
				<Row>
					<Upload {...props}>
						{
							this.state.fileList.length >= 1
								? null
								: (<div>
									<Icon type={this.state.loading
											? 'loading'
											: 'plus'}/>
									<div className="ant-upload-text">Upload</div>
								</div>)
						}
					</Upload>
				</Row>
			</Col>
			<Divider/>
		</Modal>)
	}

	pubArticle = (id) => {
		this.props.dispatch({
			type: 'article/pubArticle',
			payload: {
				article_id: id
			}
		});
	};

	cancelPubArticle = (id) => {
		this.props.dispatch({
			type: 'article/cancelPubArticle',
			payload: {
				article_id: id
			}
		});
	};

	renderSimpleForm() {
		const {getFieldDecorator} = this.props.form;
		const {authors} = this.props;
		return (<Form onSubmit={this.handleSearch} layout="inline">
			<Row gutter={{
					md: 8,
					lg: 24,
					xl: 48
				}}>
				<Col md={4} sm={12}>
					<FormItem label="作者">
						{
							getFieldDecorator('author_id')(<Select showSearch={true} placeholder="选择作者">
								{
									authors.map(author => (<Option key={author.id} value={author.id}>
										{author.nickname}
									</Option>))
								}
							</Select>)
						}
					</FormItem>
				</Col>
				<Col md={4} sm={12}>
					<FormItem label="文章状态">
						{
							getFieldDecorator('status')(<Select placeholder="请选择" style={{
									width: '100%'
								}}>
								<Option value="1">编辑中</Option>
								<Option value="2">待审核</Option>
								<Option value="3">待发布</Option>
								<Option value="4">未通过</Option>
							</Select>)
						}
					</FormItem>
				</Col>
				<Col md={4} sm={12}>
					<span className={styles.submitButtons}>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button style={{
								marginLeft: 8
							}} onClick={this.handleFormReset}>
							重置
						</Button>
					</span>
				</Col>
			</Row>
		</Form>);
	}

	renderAdvancedForm() {
		const {getFieldDecorator} = this.props.form;
		const {authors} = this.props;
		return (<Form onSubmit={this.handleSearch} layout="inline">
			<Row gutter={{
					md: 8,
					lg: 24,
					xl: 48
				}}>
				<Col md={8} sm={24}>
					<FormItem label="作者">
						{
							getFieldDecorator('author_id')(<Select showSearch="showSearch" placeholder="选择作者" optionFilterProp="children" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
								{
									authors.map(author => (<Option key={author.id} value={author.id}>
										{author.nickname}
									</Option>))
								}
							</Select>)
						}
					</FormItem>
				</Col>
				<Col md={8} sm={24}>
					<FormItem label="文章状态">
						{
							getFieldDecorator('status')(<Select placeholder="请选择" style={{
									width: '100%'
								}}>
								<Option value="1">编辑中</Option>
								<Option value="2">待审核</Option>
								<Option value="3">待发布</Option>
								<Option value="4">未通过</Option>
							</Select>)
						}
					</FormItem>
				</Col>
			</Row>
			<div style={{
					overflow: 'hidden'
				}}>
				<span style={{
						float: 'right',
						marginBottom: 24
					}}>
					<Button type="primary" htmlType="submit">
						查询
					</Button>
					<Button style={{
							marginLeft: 8
						}} onClick={this.handleFormReset}>
						重置
					</Button>
					<a style={{
							marginLeft: 8
						}} onClick={this.toggleForm}>
						收起
						<Icon type="up"/>
					</a>
				</span>
			</div>
		</Form>);
	}

	renderForm() {
		return this.state.expandForm
			? this.renderAdvancedForm()
			: this.renderSimpleForm();
	}

	render() {
		const {rule: {
				data
			}, loading, checkLoading} = this.props;
		const {selectedRows, modalVisible} = this.state;

		const my = this;

		const columns = [
			{
				title: 'ID',
				dataIndex: 'id'
			}, {
				title: '标题',
				dataIndex: 'title',
				render(val) {
					return <div style={{
							maxWidth: 300
						}}>{val}</div>
				}
			}, {
				title: '状态',
				dataIndex: 'status',
				render(val, record) {
					return (<div>
						{
							record.status === 1
								? <Row>
										<Badge status={statusMap[val - 1]} text={status[val - 1]}/>
										<Button size="small" onClick={() => my.handleSubCheck(record.id)} style={{
												marginLeft: 8
											}}>提交</Button>
									</Row>
								: record.status === 2
									? <Row>
											<Badge status={statusMap[val - 1]} text={status[val - 1]}/>
											<Button size="small" onClick={() => my.handleCheck(record)} style={{
													marginLeft: 8
												}}>审核</Button>
										</Row>
									: record.status === 3
										? record.online === 1
											? <Row>
												<Badge status={statusMap[val - 1]} text={status[4]}/>
												<Button size="small" onClick={() => my.cancelPubArticle(record.id)} style={{
														marginLeft: 8
													}}>下架</Button>
											</Row>
											: <Row>
													<Badge status={statusMap[val - 1]} text={status[val - 1]}/>
													<Button size="small" onClick={() => my.pubArticle(record.id)} style={{
															marginLeft: 8
														}}>发布</Button>
												</Row>
										: record.status === 4
											? <Row>
													<Badge status={statusMap[val - 1]} text={status[val - 1]}/>
													<Button size="small" onClick={() => my.handleSubCheck(record.id)} style={{
															marginLeft: 8
														}}>提交</Button>
												</Row>
											: null
						}
					</div>);
				}
			}, {
				title: '作者',
				dataIndex: 'author'
			}, {
				title: '创建时间',
				dataIndex: 'create_time'
			}, {
				title: '操作',
				render: (val, record) => (<Fragment>
					<a target="_blank" href={`#/article/pub-article?id=${record.id}`}>编辑</a>
					<Divider type="vertical"/>
					<a onClick={() => {
							this.handleDelete(record.id)
						}}>删除</a>
					<Divider type="vertical"/> {/* <a href="">设置</a> */}
				</Fragment>)
			}
		];

		const menu = (<Menu onClick={this.handleMenuClick} selectedKeys={[]}>
			<Menu.Item key="remove">删除</Menu.Item>
			<Menu.Item key="approval">批量审批</Menu.Item>
		</Menu>);

		const parentMethods = {
			handleAdd: this.handleAdd,
			handleModalVisible: this.handleModalVisible
		};

		return (<PageHeaderLayout title="查询表格">
			<Modal title={this.state.checkItem.title} visible={this.state.visible} footer={null} onOk={this.handleCheckOk} onCancel={this.handleCheckCancel}>
				<div className={styles.articleHtml} dangerouslySetInnerHTML={{
						__html: this.state.checkItem.content
					}}/>
				<Row style={{
						textAlign: 'center',
						marginTop: 50
					}}>
					<Button loading={checkLoading} style={{
							marginLeft: 20
						}} onClick={() => this.handleAdopt(this.state.checkItem.id)} type="primary" size="large" icon="check">审核通过</Button>
					<Button loading={checkLoading} style={{
							marginLeft: 20
						}} onClick={() => this.handleNotThrough(this.state.checkItem.id)} type="default" size="large" icon="close">审核不通过</Button>
				</Row>
			</Modal>
			<Card bordered={false}>
				<div className={styles.tableList}>
					<div className={styles.tableListForm}>{this.renderForm()}</div>
					<div className={styles.tableListOperator}>
						<a target="_blank" href="#/article/pub-article">
							<Button icon="plus" type="primary">
								新建
							</Button>
						</a>
						{
							selectedRows.length > 0 && (<span>
								<Button>批量操作</Button>
								<Dropdown overlay={menu}>
									<Button>
										更多操作
										<Icon type="down"/>
									</Button>
								</Dropdown>
							</span>)
						}
					</div>
					<StandardTable selectedRows={selectedRows} loading={loading} data={data} columns={columns} onSelectRow={this.handleSelectRows} onChange={this.handleStandardTableChange}/>
				</div>
			</Card>
			<CreateForm {...parentMethods} modalVisible={modalVisible}/>
		</PageHeaderLayout>);
	}
}
